<template>
  <div class="app-container">
    <list-admin
      ref="admin"
      :key="componentRefresh"
      v-model="listData"
      :entity-conf="entity"
      :list-display="fields"
      :disabled-actions="disabled"
      :query="query"
      :config="config"
      :actions="actions"
      :data-processor="dataProcessor"
    >
      <template v-slot:titleText>
        <span>人员管理</span>
      </template>
      <template v-slot:extraTopButton>
        <span style="margin-right: .5em">
          <el-input v-model="search.id" placeholder="id" style="width: 150px;" size="medium" clearable>
            <i slot="prefix" class="el-input__icon el-icon-search" />
          </el-input>
        </span>
        <span style="margin-right: .5em">
          <el-input v-model="search.name" placeholder="名称" style="width: 150px;" size="medium" clearable>
            <i slot="prefix" class="el-input__icon el-icon-search" />
          </el-input>
        </span>
        <span style="margin-right: .5em">
          <el-input v-model="search.phone" placeholder="电话" style="width: 150px;" size="medium" clearable>
            <i slot="prefix" class="el-input__icon el-icon-search" />
          </el-input>
        </span>
        <span style="margin-right: .5em">
          <el-select v-model="search.squad" style="width: 150px;" size="medium" clearable placeholder="小队">
            <el-option v-for="item in squads" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </span>
        <span style="margin-right: .5em">
          <el-select v-model="search.team" style="width: 150px;" size="medium" clearable placeholder="团队">
            <el-option v-for="item in teams" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </span>
        <span style="margin-right: .5em">
          <el-select v-model="search.role" style="width: 150px;" size="medium" clearable placeholder="角色">
            <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </span>
        <span style="margin-right: .5em">
          <el-select v-model="search.status" style="width: 150px;" size="medium" clearable placeholder="状态">
            <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </span>
        <el-button
          class="filterSpan"
          size="medium"
          icon="el-icon-search"
          style="margin-right: 1em"
          circle
          @click="filterGenerate();fetchData();"
        />
        <el-button v-if="config && config.list && config.list.selection" slot="reference" size="medium" type="warning" icon="el-icon-refresh" plain @click="settings()">
          批量设置
        </el-button>
      </template>
    </list-admin>

    <el-dialog
      title="设置"
      :visible.sync="dialog.visible"
      width="50%"
    >
      <div style="padding: 10px;">
        <el-form ref="form" label-width="120px">
          <el-form-item label="保证金">
            <el-input v-model="dialog.fee" type="number" min="0" />
            <div style="color:gray;font-size:16px;">所选数据未开户会申请开户，已开户则批量更新保证金</div>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button style="margin-right: 10px;" @click="dialog.visible = false">取消</el-button>
        <el-button slot="reference" type="primary" :loading="dialog.loading" @click="submit()">
          {{ dialog.loading ? '提交中 ...' : '确认' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ListAdmin from '@/components/EasyAdmin/ListAdmin'
import admin from '@/config'

export default {
  components: { ListAdmin },
  data() {
    return {
      entity: '',
      alias: '',
      config: {},
      fields: [],
      query: {},
      disabled: [],
      entityParam: this.$route.params.entityParam,
      listData: [],
      componentRefresh: 0,
      actions: [],
      filter: {},
      squads: [],
      teams: [],
      roles: [],
      options: [
        { id: 1, name: '在职' },
        { id: 2, name: '离职' }
      ],
      selections: [],
      search: {
        id: null,
        name: null,
        phone: null,
        squad: null,
        team: null,
        role: null,
        status: null
      },
      dialog: {
        visible: false,
        loading: false,
        fee: 0
      }
    }
  },
  created() {
    // Load entities data
    this.alias = 'OfficerStaff'

    if (!Object.keys(admin.entities).includes(this.alias)) {
      console.log('NO!')
    } else {
      this.config = admin.entities[this.alias]
      this.entity = Object.keys(this.config).includes('entity') ? this.config.entity : this.alias
      this.fields = this.config.list.list_display
      this.disabled = this.config.list.disabled_actions
      this.query = this.config.list.query
      this.actions = this.config.list.actions

      this.getSquads()
      this.getTeams()
      this.getRoles()
    }
  },
  methods: {
    clearDialog() {
      this.dialog.fee = 0
    },
    submit() {
      const selections = this.selections
      if (selections.length === 0) {
        this.$message.error('请选择操作数据!')
        return
      }
      if (isNaN(Number(this.dialog.fee))) {
        this.$message.error('请正确数字类型!')
        return
      }
      this.dialog.loading = true
      const data = []
      selections.map(v => {
        if (v.bond) {
          data.push({ id: v.bond.id, fee: Number(this.dialog.fee) })
        } else {
          data.push({ staff: v.id, fee: Number(this.dialog.fee) })
        }
      })
      this.axios.post(`/officer/bonds/batch-update`, data, { params: { '@mode': 'mixed', '@basis': 'id' }})
        .then((res) => {
          this.$message.success('修改成功!')
          this.dialog.visible = false
          this.clearDialog()
          this.fetchData()
        })
        .finally(() => {
          this.dialog.loading = false
        })
    },
    settings() {
      const multipleSelection = this.$refs.admin.multipleSelection
      if (multipleSelection.length > 0) {
        this.dialog.visible = true
        this.selections = multipleSelection
      } else {
        this.$message.error('请选择操作数据!')
        this.selections = []
      }
    },
    getSquads() {
      this.axios.get(`/officer/squads`, {
        params: {
          limit: 10000000
        }
      }).then(res => {
        this.squads = res.data
      })
    },
    getTeams() {
      this.axios.get(`/officer/teams`, {
        params: {
          limit: 10000000
        }
      }).then(res => {
        this.teams = res.data
      })
    },
    getRoles() {
      this.axios.get(`/officer/roles`, {
        params: {
          limit: 10000000
        }
      }).then(res => {
        this.roles = res.data
      })
    },
    fetchData() {
      this.$refs.admin.fetchData()
    },
    filterGenerate() {
      this.filter = {}
      if (this.search.id) {
        const expression = `entity.getId() == ${this.search.id}`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.name) {
        const expression = `entity.getName() matches '${this.search.name}'`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.phone) {
        const expression = `entity.getPhone() matches '${this.search.phone}'`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.squad) {
        const expression = `entity.getSquad().getId() == '${this.search.squad}'`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.team) {
        const expression = `entity.getSquad().getTeam().getId() == '${this.search.team}'`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.role) {
        const expression = `entity.getRole().getId() == '${this.search.role}'`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.status) {
        let expression = ''
        if (this.search.status > 1) {
          expression = `entity.getEnabled() == false`
        } else {
          expression = `entity.getEnabled() == true`
        }
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
    },
    dataProcessor(context, dataProcessor = {}) {
      // Loading start
      context.list = []
      context.loading = true

      const promise = [
        // Fetch Structure
        context.em.structure().then(res => { context.structure = res }),

        // Fetch Data
        context.em.list(Object.assign(
          /**
               * Combine default constant query to dynamic pager and sort
               * Pager and sort object will change in the page
               */
          {},
          context.query ? context.query : {},
          this.filter,
          context.pager,
          context.sort
        )).then(res => {
          // Assign data
          context.list = res.data
          context.paginator = res.paginator
        })
      ]

      Promise.all(promise.map(p => p.catch(e => e)))
        .then(res => { context.loading = false })
    }
  }
}
</script>

<style lang="scss" scoped>
  .filterSpan {
    margin-right: .5em;
    margin-top: .5em
  }
</style>
